package com.jt.chapter06.config;

import cn.hutool.json.JSONUtil;

import com.jt.chapter06.common.Result;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 当未登录或者token失效访问接口时，自定义返回结果
 * @author jiang tao
 * @date 2022/1/11
 * @description:
 **/
@Component
public class RestAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        httpServletResponse.setHeader("Access-Control-Allow-Origin", " http://localhost:8081");
        httpServletResponse.setHeader("Access-Control-Allow-Credentials","true");
        // 在这里值不能为 *
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, token");

        httpServletResponse.getWriter().println(JSONUtil.parse(Result.fail(e.getMessage())));
        httpServletResponse.getWriter().flush();
    }
}
